package com.eastmoney.emis.edda.domain.service.edda.impl;

import com.eastmoney.emis.datasource.redis.factory.RedisDbFactory;
import com.eastmoney.emis.edda.domain.service.edda.Cache;
import com.eastmoney.emis.edda.domain.valueobject.TimeFormatter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.domain.service.edda.impl
 * @author: 汪程程
 * @date: 2023/2/15 10:22 AM
 * @version: 1.0
 */

@Service
public class BindCheckDailyCache implements Cache<LocalDateTime> {

    public static final String REDIS_NAME = "trade";


    @Override
    public boolean add(String key) {
        if(key == null) {
            return false;
        }
        put(key, LocalDateTime.now());
        return true;
    }

    @Override
    public boolean exist(String key) {
        if(key == null) {
            return false;
        }
        return getCacheWithRedisHash().hasKey(generateKey(), key);
    }

    @Override
    public LocalDateTime getObject(String key) {
        if(key == null) {
            return null;
        }
        return getValueFromRedis(key);
    }

    private void put(String key, LocalDateTime dateTime) {
        getCacheWithRedisHash().put(generateKey(), key, dateTime.format(TimeFormatter.YYYY_MM_DD_HH_mm_ss));
        expire(generateKey());
    }

    private LocalDateTime getValueFromRedis(String key) {
        String s = getCacheWithRedisHash().get(generateKey(), key);
        return StringUtils.isEmpty(s) ? null : LocalDateTime.parse(s, TimeFormatter.YYYY_MM_DD_HH_mm_ss);
    }

    private HashOperations<String, String, String> getCacheWithRedisHash() {
        return RedisDbFactory.getStringRedisTemplate(REDIS_NAME).opsForHash();
    }

    private void expire(String hashName) {
        RedisDbFactory.getStringRedisTemplate(REDIS_NAME).expire(hashName, Duration.ofDays(1));
    }

    private String generateKey() {
        return "EDDA:HSBC:LIMIT:" + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
    }
}
